package com.benshou.bsoa.common.exception;

import com.benshou.bsoa.common.dto.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.nio.file.AccessDeniedException;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /** 处理业务异常 */
    @ExceptionHandler(BusinessException.class)
    public ResponseVo<?> handleBusinessException(BusinessException e) {
        log.info("业务异常：", e);
        return ResponseVo.fail(e.getCode(), e.getMessage());
    }

    /** 处理参数校验异常 */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseVo<?> handleValidationException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return ResponseVo.fail(message);
    }

    /** 处理Spring Security异常 */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseVo<?> handleAccessDenied(AccessDeniedException e) {
        return ResponseVo.fail("权限不足");
    }
    /** 处理所有其他异常 */
    @ExceptionHandler(Exception.class)
    public ResponseVo<?> handleGlobalException(Exception e) {
        log.info("系统异常：", e);
        return ResponseVo.fail(e.getMessage());
    }
}